

package com.hazelcast.query.impl.predicates;

import com.hazelcast.query.Predicate;
import com.hazelcast.query.impl.IndexRegistry;

/**
 * Rule based optimizer. It chains {@link Visitor}s to rewrite query.
 */
public final class RuleBasedQueryOptimizer implements QueryOptimizer {

    private final Visitor flatteningVisitor = new FlatteningVisitor();
    private final Visitor rangeVisitor = new RangeVisitor();
    private final Visitor orToInVisitor = new OrToInVisitor();
    private final Visitor compositeIndexVisitor = new CompositeIndexVisitor();
    private final Visitor evaluateVisitor = new EvaluateVisitor();

    @Override
    @SuppressWarnings("unchecked")
    public <K, V> Predicate<K, V> optimize(Predicate<K, V> predicate, IndexRegistry indexes) {
        Predicate optimized = predicate;
        if (optimized instanceof VisitablePredicate) {
            optimized = ((VisitablePredicate) optimized).accept(flatteningVisitor, indexes);
        }
        if (optimized instanceof VisitablePredicate) {
            optimized = ((VisitablePredicate) optimized).accept(rangeVisitor, indexes);
        }
        if (optimized instanceof VisitablePredicate) {
            optimized = ((VisitablePredicate) optimized).accept(orToInVisitor, indexes);
        }
        if (optimized instanceof VisitablePredicate) {
            optimized = ((VisitablePredicate) optimized).accept(compositeIndexVisitor, indexes);
        }
        if (optimized instanceof VisitablePredicate) {
            optimized = ((VisitablePredicate) optimized).accept(evaluateVisitor, indexes);
        }
        return optimized;
    }

}
